package com.sugar.psych.assessment.module.business.config.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.sugar.psych.assessment.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.psych.assessment.module.business.enums.ErrorCodeConstants.AI_CHAT_REPLY_ERROR;

@Slf4j
@Component
@ServerEndpoint(value = "/chat-message/{userId}/{recordId}")
public class WebSocketService {

    /**
     * 存放所有在线的客户端
     */
    private static final Map<String, Session> CLIENTS = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("recordId") String recordId) {
        log.info("客户端建立连接");
        CLIENTS.put(userId + recordId, session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId, @PathParam("recordId") String recordId) {
        CLIENTS.remove(userId + recordId);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId, @PathParam("userId") String recordId) {
        //System.out.println("收到消息：" + message);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") String userId, @PathParam("userId") String recordId) {
        log.error("发生错误：{},错误信息：{}", userId, error.getMessage());
        CLIENTS.remove(userId + recordId);
    }

    /**
     * 群发消息
     *
     * @param message 消息内容
     */
    public void sendMsgAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : CLIENTS.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }

    /**
     * 单发消息
     *
     * @param message 消息内容
     */
    public void sendMsgOne(String message, String userId, String recordId) {
        Session session = CLIENTS.get(userId + recordId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("消息发送异常：", e);
                throw exception(AI_CHAT_REPLY_ERROR);
            }
        }
    }
}
